﻿(function ($) {
    $.extend($, {
        fileUpload: function (options) {
            var para = {
                multiple: false,
                filebutton: ".filePicker",
                uploadButton: null,
                url: "/home/MUploadImg",
                filebase: "mfile",//mvc后台需要对应的名称
                auto: true,
                previewZoom: null,
                maxWidth:300,
                uploadStart: function (file, src) {
                    console.log("uploadStart", file);
                },
                uploadComplete: function (file, res) {
                    console.log("uploadComplete", res);
                },
                uploadError: function (file, err) {
                    console.log("uploadError", err);
                },
                onProgress: function (file, percent) {  // 提供给外部获取单个文件的上传进度，供外部实现上传进度效果
                    console.log(percent);
                },
            };
            var oldfile;
            para = $.extend(para, options);

            var $self = $(para.filebutton);
            //先加入一个file元素
            var multiple = "";  // 设置多选的参数
            para.multiple ? multiple = "multiple" : multiple = "";
           // $self.parent().remove("#fileImage");
            $self.css('position', 'relative');
            $self.append('<input id="fileImage"  style="opacity:0;position:absolute;top: 0;left: 0;width:100%;height:100%"  type="file" size="30" name="fileselect[]" ' + multiple + '>');
            var doms = {
                "fileToUpload": $self.parent().find("#fileImage"),
            };
          

            var core = {
                fileSelected: function () {
                    var files = $self.parent().find("#fileImage")[0].files;
                    var count = files.length;
                    console.log("共有" + count + "个文件");
                    for (var i = 0; i < count; i++) {
                        var item = files[i];
                        console.log(item.size);
                        if (para.auto) {
                            core.uploadFile(item);
                        }
                        core.previewImage(item);
                    }
                },

                uploadFile: function (file) {
                    console.log("开始上传");
                    var formdata = new FormData();

                    formdata.append(para.filebase, file);//这个名字要和mvc后台配合
                    var img = new Image();
                    img.file = file;
                    var reader = new FileReader();
                    var blret = true;
                    reader.onload = (function (aImg) {
                        return function (e) {
                            aImg.src = e.target.result;
                            blret = para.uploadStart(file, e.target.result);
                            if (blret == false) {
                                return;
                            }
                            var xhr = new XMLHttpRequest();
                            xhr.upload.addEventListener("progress", function (e) {

                                var percentComplete = Math.round(e.loaded * 100 / e.total);
                                para.onProgress(file, percentComplete.toString() + '%');
                            });
                            xhr.addEventListener("load", function (e) {
                                para.uploadComplete(file, xhr.responseText);

                                core.reInit();

                            });
                            xhr.addEventListener("error", function (e) {
                                para.uploadError(file, e);
                                core.reInit();
                            });

                            xhr.onreadystatechange = function () {
                                if (xhr.readyState == 4) {
                                    if (xhr.status != 404) {
                                    } else {
                                        //handle...
                                        para.uploadError(file, 404);
                                        core.reInit();
                                    }
                                }
                            };
                            xhr.onerror = function (error) {
                                para.uploadError(file, error);
                                console.log(error);
                                core.reInit();
                            };
                            xhr.ontimeout = function (error) {
                                para.uploadError(file, error);
                                console.log("timeout", error);
                                core.reInit();
                            };
                            xhr.open("post", para.url, true);
                            //xhr.setRequestHeader("X_FILENAME", file.name);
                            try {
                                xhr.send(formdata);

                            } catch (e) {
                                para.uploadError(file, e);
                                core.reInit();
                            }
                        };
                    })(img);
                    reader.readAsDataURL(file);

                    /*
                    if (blret == false) {
                        return;
                    }
                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (e) {

                        var percentComplete = Math.round(e.loaded * 100 / e.total);
                        para.onProgress(file, percentComplete.toString() + '%');
                    });
                    xhr.addEventListener("load", function (e) {
                        para.uploadComplete(file, xhr.responseText);

                        core.reInit();
                   
                    });
                    xhr.addEventListener("error", function (e) {
                        para.uploadError(file, e);
                        core.reInit();
                    });

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4) {
                            if (xhr.status != 404) {
                            } else {
                                //handle...
                                para.uploadError(file, 404);
                                core.reInit();
                            }
                        }
                    };
                    xhr.onerror = function (error) {
                        para.uploadError(file, error);
                        console.log(error);
                        core.reInit();
                    };
                    xhr.ontimeout = function (error) {
                        para.uploadError(file, error);
                        console.log("timeout", error);
                        core.reInit();
                    };
                    xhr.open("post", para.url, true);
                    //xhr.setRequestHeader("X_FILENAME", file.name);
                    try{
                        xhr.send(formdata);

                    } catch (e) {
                        para.uploadError(file, e);
                        core.reInit();
                    }
                    */
                },
                uploadFiles: function () {
                    var files = $self.parent().find("#fileImage")[0].files;
                    for (var i = 0; i < files.length; i++) {
                        core.uploadFile(files[i]);
                    }
                },
                previewImage: function (file) {
                    if (!para.previewZoom) return;
                    var img = document.createElement("img");
                    img.file = file;
                    $(para.previewZoom).append(img);
                    // 使用FileReader方法显示图片内容
                    var reader = new FileReader();
                    reader.onload = (function (aImg) {
                        return function (e) {
                            aImg.src = e.target.result;
                        };
                    })(img);
                    reader.readAsDataURL(file);
                },
                reInit: function () {
                    $self.children("#fileImage").remove();
                    $self.append('<input id="fileImage"  style="opacity:0;position:absolute;top: 0;left: 0;width:100%;height:100%"  type="file" size="30" name="fileselect[]" ' + multiple + '>');
                    $self.parent().find("#fileImage").on("change", function () {
                        console.log("选中了文件");
                        core.fileSelected();
                    });
                }
                

            }
            doms.fileToUpload.on("change", function () {
                //doms.progress.find("span").width("0");
             
                console.log("选中了文件");
                core.fileSelected();
            });

            console.log("初始化!");
            //绑定事件

            $(document).on("click", para.filebutton, function () {
                console.log("clicked");
                //doms.fileToUpload.click();
            });
            if (para.uploadButton) {
                $(document).on("click", para.uploadButton, function () {
                    core.uploadFiles();
                });
            }
        }
    });
})(Zepto);